<template>
  <div>
    <a-alert type="warning" show-icon style="margin-bottom: 18px">
      <template #description>
        无需臃肿的SDK，只需几行代码即可对接SMTP邮件服务。
        <a
          href="https://doc.21ds.cn/detail?doc=4731341806141859/4823388355822325"
          target="_blank"
          rel="noopener noreferrer"
          >对接文档</a
        >
      </template>
    </a-alert>
    <div class="table-page-search-wrapper">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="16">
          <a-form layout="inline" :model="listQuery">
            <a-form-item label="搜索项">
              <a-input v-model:value="listQuery.title" placeholder="输入备注/ID搜索..." />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchSubmit"> 搜索 </a-button>
            </a-form-item>
            <a-form-item>
              <a-button
                v-permission="{ action: 'del_email_server_batch' }"
                type="primary"
                danger
                :disabled="selectedRowKeys.length === 0"
                @click="deleteSelect"
              >
                <template #icon>
                  <DeleteOutlined />
                </template>
                删除所选
              </a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="8">
          <div style="margin-right: 0px; float: right; display: flex; align-item: center">
            <a-tooltip placement="top">
              <template #title>
                <span>刷新列表</span>
              </template>
              <a-button @click="reloadList">
                <template #icon><SyncOutlined /></template>
              </a-button>
            </a-tooltip>
            <a-button
              v-permission="{ action: 'email_server_add' }"
              type="primary"
              style="margin-left: 12px"
              @click="addNewData"
            >
              <template #icon><PlusOutlined /></template> 新增邮件服务器
            </a-button>
          </div>
        </a-col>
      </a-row>
    </div>
    <a-table
      :columns="columns"
      :rowKey="(record) => record._id"
      :dataSource="dataList.data"
      :loading="loading"
      :pagination="pagination"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      @change="handleTableChange"
    >
      <template #status="{ text: record }">
        <a-tag v-if="record == 1" color="green">启用</a-tag>
        <a-tag v-if="record == -1" color="red">禁用</a-tag>
        <a-tag v-if="record == 0" color="red">禁用</a-tag>
      </template>
      <template #action="{ text: record }">
        <a v-permission="{ action: 'email_server_add' }" @click="email_server_edit(record)"
          ><EditOutlined /> 编辑</a
        >
        <a-divider type="vertical" />
        <a @click="email_server_test(record)"> 测试</a>
        <a-divider v-permission="{ action: 'email_server_ext' }" type="vertical" />
        <a-dropdown>
          <a v-permission="{ action: 'email_server_ext' }" class="ant-dropdown-link">
            更多 <DownOutlined
          /></a>
          <template #overlay>
            <a-menu>
              <a-menu-item v-permission="{ action: 'email_server_copy' }">
                <a @click="email_server_copy(record)"><CopyOutlined /> 复用</a>
              </a-menu-item>
              <a-menu-item v-permission="{ action: 'email_server_del' }" style="color: red">
                <a @click="email_server_delete(record)"><DeleteOutlined /> 删除</a>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
    </a-table>
    <a-drawer
      width="50%"
      :title="drawerTitle"
      placement="right"
      :open="drawerShow"
      @close="
        () => {
          drawerShow = false
        }
      "
    >
      <template #extra>
        <a-button
          style="margin-right: 8px"
          @click="
            () => {
              drawerShow = false
            }
          "
          >取消</a-button
        >
        <a-button type="primary" @click="addServer">提交</a-button>
      </template>
      <a-form
        ref="formRef"
        :model="FormState"
        :rules="FormRule"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-form-item has-feedback required label="标题">
          <a-textarea v-model:value="FormState.title" show-count placeholder="请输入标题(备注)" />
        </a-form-item>
        <a-form-item has-feedback required label="SMTP服务器">
          <a-input v-model:value="FormState.smtp_server" placeholder="请输入SMTP服务器地址" />
        </a-form-item>
        <a-form-item has-feedback required label="SMTP用户名">
          <a-input
            v-model:value="FormState.smtp_username"
            show-count
            placeholder="请输入SMTP用户名"
          />
        </a-form-item>
        <a-form-item has-feedback required label="SMTP密码">
          <a-input-password
            v-model:value="FormState.smtp_password"
            placeholder="请输入SMTP密码(注：本项编辑时不透出，如需修改，直接将新密码填写此处提交即可)"
          />
        </a-form-item>
        <a-form-item has-feedback required label="启用SSL">
          <a-switch
            v-model:checked="FormState.is_ssl_bool"
            checked-children="是"
            un-checked-children="否"
          />
        </a-form-item>
        <a-form-item has-feedback required label="端口号">
          <a-input-number
            v-model:value="FormState.port"
            placeholder="请输入端口号"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item has-feedback required label="发件人邮箱">
          <a-input v-model:value="FormState.sender" placeholder="请输入发件人邮箱" />
        </a-form-item>
        <a-form-item has-feedback required label="发件人姓名">
          <a-input v-model:value="FormState.sender_name" placeholder="请输入发件人姓名" />
        </a-form-item>
        <a-form-item has-feedback required label="回复邮箱">
          <a-input v-model:value="FormState.reply_email" placeholder="请输入回复邮箱地址" />
        </a-form-item>
        <a-form-item label="是否启用" has-feedback required name="status">
          <a-radio-group v-model:value="FormState.status" name="status">
            <a-radio :key="1" :value="1">启用</a-radio>
            <a-radio :key="-1" :value="-1">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="SecretKey" name="server_secret">
          <a-input-search
            v-model:value="FormState.server_secret"
            placeholder="点击右侧“获取密钥”按钮进行获取"
            enter-button="获取密钥"
            @search="resetSecret"
          />
        </a-form-item>
      </a-form>
    </a-drawer>
    <a-modal v-model:open="modalVisible" title="邮件测试" okText="发送" @ok="emailTest">
      <a-input v-model:value="testEmail" placeholder="请输入收件人邮箱地址" />
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, ref } from 'vue'
import {
  Row,
  Col,
  Modal,
  Divider,
  Image,
  Drawer,
  Switch,
  InputPassword,
  InputNumber
} from 'ant-design-vue'
import {
  SyncOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DownOutlined,
  CopyOutlined
} from '@ant-design/icons-vue'
import {
  delServerItem,
  getServerList,
  editServerInfo,
  testServer,
  delServerBatch
} from '@/api/email'
import { useRouter } from 'vue-router'
import { randomString } from '@/utils/common'
import { requestFailed, requestSuccess } from '@/utils/feedback'

export default defineComponent({
  name: 'AdsList',
  components: {
    SyncOutlined,
    PlusOutlined,
    CopyOutlined,
    DownOutlined,
    EditOutlined,
    DeleteOutlined,
    [Modal.name]: Modal,
    [Row.name]: Row,
    [Drawer.name]: Drawer,
    [Switch.name]: Switch,
    [InputPassword.name]: InputPassword,
    [InputNumber.name]: InputNumber,
    [Col.name]: Col,
    [Image.name]: Image,
    [Divider.name]: Divider
  },
  setup() {
    const formRef = ref()
    const router = useRouter()
    const state = reactive<any>({
      loading: true,
      drawerShow: false,
      modalVisible: false,
      testEmail: '',
      drawerTitle: '邮件服务器详情',
      testServer: {
        _id: ''
      },
      dataList: [],
      selectedRowKeys: [],
      selectedKeysPage: {},
      listQuery: {
        pageNo: 1,
        pageSize: 15,
        title: ''
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      pagination: {
        pageSizeOptions: ['15', '30', '50'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSize: 15,
        current: 1
      },
      columns: [
        {
          title: 'ID',
          dataIndex: '_id'
        },
        {
          title: '标题',
          dataIndex: 'title'
        },
        {
          title: '状态',
          dataIndex: 'status',
          slots: { customRender: 'status' }
        },
        {
          title: '添加时间',
          dataIndex: 'create_time'
        },
        {
          title: '操作',
          width: '250px',
          slots: { customRender: 'action' }
        }
      ]
    })
    onMounted(() => {
      getDataList()
    })
    function resetSecret() {
      FormState.server_secret = randomString(64)
    }

    function handleTableChange(e) {
      state.loading = true
      state.pagination.pageSize = e.pageSize
      state.listQuery.pageSize = e.pageSize
      state.listQuery.pageNo = e.current
      state.pagination.current = e.current
      getDataList()
    }

    const FormState = reactive<any>({
      _id: '',
      title: '',
      smtp_server: '',
      smtp_password: '',
      port: '',
      is_ssl_bool: '',
      sender: '',
      smtp_username: ''
    })
    const FormRule = {
      title: [{ required: true, message: '请输入标题(备注)', trigger: ['blur', 'change'] }],
      smtp_username: [{ required: true, message: '请输入SMTP用户名', trigger: ['blur', 'change'] }],
      is_ssl_bool: [{ required: true, message: '请选择是否启用SSL', trigger: ['blur', 'change'] }],
      port: [{ required: true, message: '请输入端口号', trigger: ['blur', 'change'] }],
      sender: [{ required: true, message: '请输入发件人邮箱', trigger: ['blur', 'change'] }],
      smtp_server: [
        { required: true, message: '请输入SMTP服务器地址', trigger: ['blur', 'change'] }
      ]
    }

    function reloadList() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }

    function searchSubmit() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }

    function getDataList() {
      getServerList(state.listQuery).then((res) => {
        state.loading = false
        state.dataList = res
        state.pagination.total = res.totalCount
      })
    }

    function email_server_test(item) {
      state.modalVisible = true
      state.testServer = item
    }
    function email_server_copy(itemData) {
      for (let item in FormState) {
        FormState[item] = ''
      }
      state.drawerTitle = '复制邮件服务器'
      for (let item in itemData) {
        if (item != '_id' && item != 'server_secret') {
          let copyTips = item == 'title' ? ' - 复制' : ''
          FormState[item] = itemData[item] + copyTips
        }
      }
      state.drawerShow = true
    }
    function email_server_edit(res) {
      state.drawerTitle = '编辑邮件服务器'
      for (let item in FormState) {
        FormState[item] = ''
      }
      for (let item in res) {
        FormState[item] = res[item]
      }
      state.drawerShow = true
    }
    function addNewData() {
      for (let item in FormState) {
        FormState[item] = ''
      }
      state.drawerTitle = '新增邮件服务器'
      state.drawerShow = true
    }
    function emailTest() {
      Modal.confirm({
        title: '确认向此邮箱发送测试邮件?',
        content: '【' + state.testEmail + '】',
        onOk() {
          testServer({ id: state.testServer._id, email: state.testEmail }).then((res) => {
            if (res.code === 200) {
              state.modalVisible = false
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    function email_server_delete(data) {
      Modal.confirm({
        title: '确认永久删除本服务器?',
        content: '【' + data._id + '】',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delServerItem({ id: data._id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              getDataList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    const addServer = () => {
      formRef.value
        .validate()
        .then(() => {
          FormState.is_ssl = FormState.is_ssl_bool == true ? 1 : 0
          editServerInfo(FormState).then((res) => {
            if (res.code === 200) {
              requestSuccess(res)
              formRef.value.resetFields()
              state.loading = true
              state.drawerShow = false
              reloadList()
            } else {
              requestFailed(res)
            }
          })
        })
        .catch(() => {
          return false
        })
    }
    function deleteSelect() {
      Modal.confirm({
        title: '确认批量删除所选内容?',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delServerBatch({ ids: state.selectedRowKeys })
            .then((res) => {
              if (res.code === 200) {
                state.loading = true
                reloadList()
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.selectedRowKeys = []
            })
        }
      })
    }
    const onSelectChange = (selectedRowKeys) => {
      state.selectedKeysPage[state.listQuery.pageNo] = selectedRowKeys
      let nowList: any[] = []
      for (const key in state.selectedKeysPage) {
        nowList = nowList.concat(state.selectedKeysPage[key])
      }
      const uniqueList = [...new Set(nowList)]
      state.selectedRowKeys = uniqueList
    }
    return {
      ...toRefs(state),
      handleTableChange,
      deleteSelect,
      onSelectChange,
      reloadList,
      searchSubmit,
      email_server_delete,
      formRef,
      email_server_copy,
      addServer,
      FormState,
      resetSecret,
      FormRule,
      emailTest,
      addNewData,
      router,
      email_server_edit,
      email_server_test,
      getDataList
    }
  }
})
</script>

<style scoped></style>
